package com.vocabulary.controller;

import com.vocabulary.dto.VocabularyEstimateDto;
import com.vocabulary.dto.WordResponseDto;
import com.vocabulary.service.VocabularyEstimator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.sql.DataSource;
import java.sql.Connection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/vocabulary")
@CrossOrigin(origins = "*")
public class VocabularyController {

    @Autowired
    private DataSource dataSource;

    @PostMapping("/estimate")
    public ResponseEntity<VocabularyEstimateDto> estimateVocabulary(@RequestBody List<WordResponseDto> responses) {
        try (Connection connection = dataSource.getConnection()) {
            VocabularyEstimator estimator = new VocabularyEstimator(connection);
            
            // 转换DTO到服务层对象
            List<VocabularyEstimator.WordResponse> wordResponses = responses.stream()
                .map(dto -> new VocabularyEstimator.WordResponse(
                    new VocabularyEstimator.Word(dto.getWord(), dto.getDifficultyLevel()),
                    dto.isKnown()
                ))
                .collect(Collectors.toList());

            // 调用估算算法
            VocabularyEstimator.VocabularyEstimate estimate = estimator.estimateVocabulary(wordResponses);
            
            // 转换结果到DTO
            VocabularyEstimateDto result = new VocabularyEstimateDto(
                estimate.getEstimatedSize(),
                estimate.getConfidenceInterval().getLowerBound(),
                estimate.getConfidenceInterval().getUpperBound(),
                estimate.getCorrectRate()
            );
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }

    @GetMapping("/next-word")
    public ResponseEntity<WordResponseDto> getNextWord(
            @RequestParam(defaultValue = "4") int abilityLevel,
            @RequestParam(required = false) String usedWords) {
        try (Connection connection = dataSource.getConnection()) {
            VocabularyEstimator estimator = new VocabularyEstimator(connection);
            
            // 转换已使用单词列表
            Set<String> usedWordsSet = new java.util.HashSet<>();
            if (usedWords != null && !usedWords.isEmpty()) {
                String[] words = usedWords.split(",");
                for (String word : words) {
                    if (!word.trim().isEmpty()) {
                        usedWordsSet.add(word.trim());
                    }
                }
            }
            
            // 获取下一个单词
            VocabularyEstimator.Word nextWord = estimator.generateAdaptiveTest(1, abilityLevel, usedWordsSet);
            
            if (nextWord != null) {
                WordResponseDto result = new WordResponseDto(
                    nextWord.getWord(),
                    nextWord.getDifficultyLevel(),
                    false // 默认不认识
                );
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }
} 